# 文件名: ex6_playwright
# 当前用户: shiping.zheng
# 当前日期: 2025/1/10
# 当前时间: 13:44
# 项目名称: Flag
"""
模块描述:
    playwright同一个异步上下文管理器，多个上下文cookies复用，避免重复登录
"""
import asyncio
from playwright.async_api import async_playwright
from PIL import Image
import pytesseract
import time

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        # 第一个上下文：登录并保存 cookies
        first_context = await browser.new_context()
        page = await first_context.new_page()
        await page.goto("https://xuntian-test1.tclpv.com/getechLogin")
        await page.get_by_placeholder("请输入用户名").fill("admin")
        await page.get_by_placeholder("请输入密码").fill("tcl123")
        # 使用角色选择器定位验证码图片
        captcha_element = page.get_by_role("img")
        # await captcha_element.click()
        # 获取图片位置
        bounding_box = await captcha_element.bounding_box()  # 确保使用 await
        print("Captcha position:", bounding_box)
        # 保存验证码图片
        await captcha_element.screenshot(path=r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
        # 使用 Tesseract 识别验证码
        captcha_image = Image.open(r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
        captcha_text = pytesseract.image_to_string(captcha_image).strip()  # 去除空格和换行
        print("Captcha text:", captcha_text)
        await page.get_by_placeholder("请输入左图结果").fill(captcha_text)
        await page.get_by_role("button", name="登录").click()
        # 等待页面加载完成
        await page.wait_for_load_state('networkidle')
        # 保存 cookies
        cookies = await first_context.cookies()
        print("Saved cookies:", cookies)
        # 关闭第一个上下文
        await first_context.close()
        # 第二个上下文：加载 cookies 并访问页面
        second_context = await browser.new_context()
        await second_context.add_cookies(cookies)
        page2 = await second_context.new_page()
        await page2.goto('https://xuntian-test1.tclpv.com/operationCenter/equipmentCenter')
        # 检查是否登录成功
        await page2.wait_for_load_state('networkidle')
        print("Page loaded with cookies")
        # 关闭第二个上下文
        await second_context.close()
        # 关闭浏览器
        await browser.close()
asyncio.run(main())